#include <sys/inotify.h>
#include <stdio.h>
#include <errno.h>
#include <stdlib.h>
#include <limits.h>
#include <signal.h>

void signal_func(int sig)
{
  fprintf(stderr, "Signal %d catched\n", sig);
}

int main(int argc, char ** argv)
{
  int exitcode;
  int i;
  int fd;
  int wd;
  char evt[sizeof(struct inotify_event)+PATH_MAX+1];
  int sig_max;
  
  if(argc!=2)
    {
      fprintf(stderr, "Usage: inotify <abs_path_to_watch>\n");
      return -1;
    }

  sig_max=32;
#ifdef SIG_MAX
  sig_max=SIG_MAX;
#endif /*SIG_MAX*/
  for(i=0;i<sig_max;i++)
    {
      signal(i, signal_func);
    }

  fd = inotify_init1(IN_CLOEXEC);
  if(fd<0)
    {
      exitcode=errno;
      fprintf(stderr, "Could not initialize inotify.\n");
      return exitcode;
    }

  wd = inotify_add_watch(fd, argv[1], IN_MOVED_TO);
  if(wd<0)
    {
      exitcode=errno;
      fprintf(stderr, "Could not add watch for %s.\n", argv[1]);
      return exitcode;
    }
  
  while(read(fd, evt, sizeof(evt))>0 || errno==EINTR)
    {
      if(errno!=EINTR)   /*if read is interrupted by signal, try again.*/
	{
	  fprintf(stdout, "File %s is moved into %s\n",   ((struct inotify_event *)evt)->name, argv[1]);
	}
    }
  
  exitcode=errno;
  fprintf(stderr, "Error while read from inotify.\n");

  return exitcode;
}

